<?php
// 帮助类，可以直接在项目里面使用
// 应用公共文件
use phpmailer\phpmailer;
use think\Env;
use app\api\extra\Msgstr;

/** 快捷操作获取error */
function ConstStr($str){
    return Msgstr::getErrorStr($str);
}

/** 快捷操作返回Errcode */
function ConstErrCode($str){
    return Msgstr::getErrorStr($str,1);
}

/** 快捷操作获取code */
function ConstCode($str){
    return Msgstr::getErrorStr($str,2);
}

/**
 * 替换某个字符
 * str:要替换的字符串
 * num:第几个字符串
 * rep:替换的名字
 */
function my_str_replace($str,$num,$rep){
    if(strlen($str)<$num)
        return false;
    $str1 = substr($str,0,$num-1);    
    $str2 = substr($str,$num);  
    return $str1.$rep.$str2;  
}

/** 判断邮箱是否正确 */
function isEmail($email=""){
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    if ( preg_match( $pattern, $email )){
        return true;
    }
    return false;
}
/**
 * 格式化时间距离现在过了多久
 */
function madate($time=""){
    $text = "";
    $time = empty($time) || $time>time()?time():intval($time);
    // 时间差（秒）
    $t = time()-$time;
    // 是否跨年
    $y = date("Y",$time)-date('Y',time());
    switch($t){
        case $t==0:
            $text = '刚刚';
            break;
        case $t<60:
            $text = $t.'秒前';
            break;
        case $t < 60*60:
            $text = floor($t/60).'分钟前';
            break;
        case $t < 60*60*24:
            $text = floor($t / (60*60))."小时前";
            break;
        case $t < 60*60*24*3:
            $text = floor($t/(60*60*24))== 1?'昨天'.date('H:i',$time):'前天'.date('H:i',$time);//昨天前天
            break;
        case $t < 60*60*24*30:
            $text = date('m月d日 H:i',$time);
            break;
        case $t < 60 * 60 * 24 * 365 && $y==0:
            $text = date('m月d日 H:i',$time);
            break;
        default:
            $text = date('Y-m-d H:i',$time);
            break;
    }
    return $text;

}

/**
 * 高亮搜索的关键字
 */
function highlight_text($str,$word,$color = "#4285f4"){
    foreach($str as $k=>$v){
        $data[$k]['title'] = str_replace($word,"<b style ='color:$color;'>$word</b>",$v['title']);
    }
    return $str;
}

/**
 * 发送邮箱
 * @param type $data 邮箱队列数据 包含邮箱地址 内容
 */
function sendEmail($data = []){
    Vendor('phpmailer.phpmailer');
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host = Env::get('mail_host'); //SMTP服务器 以126邮箱为例子
    $mail->Port = Env::get('mail_post'); //邮件发送端口
    $mail->SMTPAuth = Env::get('mail_smtpauth'); //启用SMTP认证
    $mail->SMTPSecure = Env::get('mail_smtpsecure'); // 设置安全验证方式为ssl
    $mail->CharSet = Env::get('mail_charset'); //字符集
    $mail->Encoding = Env::get('mail_encoding'); //编码方式
    $mail->Username = Env::get('mail_username'); //你的邮箱
    $mail->Password = Env::get('mail_password'); //你的密码
    $mail->Subject = Env::get('mail_subject'); //邮件标题
    $mail->From = Env::get('mail_from'); //发件人地址（也就是你的邮箱）
    $mail->FromName = Env::get('mail_fromName'); //发件人姓名

    if ($data && is_array($data)) {
        foreach ($data as $k => $v) {
            $mail->AddAddress($v['user_email'], "亲"); //添加收件人（地址，昵称）
            $mail->IsHTML(true); //支持html格式内容
            $mail->Body = $v['content']; //邮件主体内容
            //发送成功就删除
            if ($mail->Send()) {
                return true;
            } else {
                return $mail->ErrorInfo; // 输出错误信息
            }
        }
    }
}

/** access_token 生成器 */
function buildAccessToken(){
    //生成种子
    $str_pol = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
    return substr(str_shuffle($str_pol), 0, 6);
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0){
    $type      = $type ? 1 : 0;
    static $ip = null;
    if (null !== $ip) {
        return $ip[$type];
    }

    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) {
            unset($arr[$pos]);
        }

        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function think_ucenter_md5($str, $key = 'rest_api'){
    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data){
    //数据类型检测
    if (!is_array($data)) {
        $data = (array) $data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 对数组按照某个字段进行排序
 * @author ning
 * @DateTime 2016-07-06T17:13:05+0800
 * @param    [type]                   $records [description]
 * @param    [type]                   $field   [description]
 * @param    boolean                  $reverse [description]
 * @return   [type]                            [description]
 */
function record_sort($records, $field, $reverse = false){
    $hash = array();
    foreach ($records as $key => $record) {
        $hash[$record[$field] . $key] = $record;
    }
    ($reverse) ? krsort($hash) : ksort($hash);
    $records = array();
    foreach ($hash as $record) {
        $records[] = $record;
    }
    return $records;
}

/**
 * 截取中文字符串
 * @author ning
 * @DateTime 2016-07-21T16:14:08+0800
 * @param    [type]                   $str     [description]
 * @param    integer                  $start   [description]
 * @param    [type]                   $length  [description]
 * @param    string                   $charset [description]
 * @param    boolean                  $suffix  [description]
 * @return   [type]                            [description]
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true){
    if (function_exists("mb_substr")) {
        $slice = mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice . '...' : $slice;
}

/**
 *根据时间戳得到中文的星期
 *@date 2015/09/02 14:42
 *@param int _timeStamp 时间戳
 *@return string 星期N
 */
function getCnWeekName($_timeStamp){
    switch (date('N', $_timeStamp)) {
        case '1':return '星期一';
        case '2':return '星期二';
        case '3':return '星期三';
        case '4':return '星期四';
        case '5':return '星期五';
        case '6':return '星期六';
        case '7':return '星期日';
    }
}

//用来生成随机账号
function rand_name($pw_length = 8){
    $randpwd = '';
    for ($i = 0; $i < $pw_length; $i++) {
        $randpwd .= mt_rand(0, 9);
    }
    return $randpwd;
}
//用来生成随机账号的密码
function rand_pw($length = 6){
// 密码字符集，可任意添加你需要的字符
    $chars    = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}

/**
 * 是否微信访问
 * @return boolean
 */
function im_weixin(){
    return (bool) strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'micromessenger');
}

/**
 * 将内容进行UNICODE编码，编码后的内容格式：YOKA\王 （原始：YOKA王）
 * @param string $s 原始字符串
 * @return string
 */
function unicodeencode($s){
    $ss  = @iconv('UTF-8', 'UCS-2', $s);
    $s   = $ss ? $ss : $s;
    $len = strlen($s);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2) {
        $c  = $s[$i];
        $c2 = $s[$i + 1];
        if (ord($c) > 0) {
            // 两个字节的文字
            $str .= '\u' . base_convert(ord($c), 10, 16) . base_convert(ord($c2), 10, 16);
        } else {
            $str .= $c2;
        }
    }
    return $str;
}
/**
 * unicode解码
 * @param string $str unicode字符串
 * @return string
 */
function unicodedecode($str){
    preg_match_all('/\\\u([[:alnum:]]{4})/', $str, $a);
    foreach ($a[1] as $uniord) {
        $dec = hexdec($uniord);
        $utf = '';
        if ($dec < 128) {
            $utf = chr($dec);
        } else if ($dec < 2048) {
            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        } else {
            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
        $str = str_replace('\u' . $uniord, $utf, $str);
    }
    return ($str);
}

function httpPost($url, $data = null){
    $ch = curl_init();
    //curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $temp = curl_exec($ch);
    curl_close($ch);
    return $temp;
}

function httpGet($url, $data = null){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    curl_close($ch);
    return $tmpInfo;
}

/**
 * 根据搜当前地址获取半径内
 * @param $lng 经度 $lat 伟度
 * @param $distance 半径千米
 */

function returnSquarePoint($lng, $lat, $distance = 1.8){
    $dlng = 2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance / EARTH_RADIUS;
    $dlat = rad2deg($dlat);
    return array(
        'left-top'     => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
        'right-top'    => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
        'left-bottom'  => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
        'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng),
    );
}

/**
 * 获取两点间距离
 * @param $lng 经度 $lat 伟度
 * @param 返回米
 */

function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2){
    $earthRadius = 6367000; //approximate radius of earth in meters
    $pi = pi();
    $lat1 = ($lat1 * $pi) / 180;
    $lng1 = ($lng1 * $pi) / 180;
    $lat2 = ($lat2 * $pi) / 180;
    $lng2 = ($lng2 * $pi) / 180;
    $calcLongitude      = $lng2 - $lng1;
    $calcLatitude       = $lat2 - $lat1;
    $stepOne            = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo            = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    if ($len_type > 1) {
        $calculatedDistance /= 1000;
    }
    return round($calculatedDistance, $decimal);
}

// 验证是否固话或者手机
function isTel($str){
    return isMobilePhone($str) || isTelPhone($str);
}
// 验证时候手机
function isMobilePhone($str){
    if (is_numeric($str) && $str > 13000000000 && $str < 19999999999) {
        return true;
    }
    return false;
}
// 验证是否固话
function isTelPhone($str){
    if(is_numeric($str) && $str > 1000000 && $str  < 9999999)
        return true;
    if (preg_match("/^(010|02\d{1}|0[3-9]\d{2})(-{0,1})\d{7,9}(-\d+)?$/", $str))
        return true;
    return false;
}

//返回订单号
function getOrderNum($adcode){
    static $randomCode;
    $time = time();
    if (is_null($randomCode)) {
        $randomCode = mt_rand('100', '900');
    } else {
        $randomCode += 1;
    }
    return $adcode . $time . $randomCode;
}

/**
 * 加密函数
 * @param string $txt 需要加密的字符串
 * @param string $key 密钥
 * @return string 返回加密结果
 */
function encrypt($txt, $key = ''){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="x6g6ZWm2G9gvr0BopOq3kRIxsZ6rm";
    $nh1 = rand(0,64);
    $nh2 = rand(0,64);
    $nh3 = rand(0,64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;$i = 0;
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
    $txt = base64_encode(time().'_'.$txt);
    $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
    $tmp = '';
    $j=0;$k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
    return $tmp;
}
/**
 * 解密函数
 * @param string $txt 需要解密的字符串
 * @param string $key 密匙
 * @return string 字符串类型的返回结果
 */
function decrypt($txt, $key = '', $ttl = 0){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="x6g6ZWm2G9gvr0BopOq3kRIxsZ6rm";
    $knum = 0;$i = 0;
    $tlen = @strlen($txt);
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars,$ch1);
    $txt = @substr_replace($txt,'',$knum % $tlen--,1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars,$ch2);
    $txt = @substr_replace($txt,'',$nh1 % $tlen--,1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars,$ch3);
    $txt = @substr_replace($txt,'',$nh2 % $tlen--,1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
    $tmp = '';
    $j=0; $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
        while ($j<0) $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
    $tmp = trim(base64_decode($tmp));
    if (preg_match("/\d{10}_/s",substr($tmp,0,11))){
        if ($ttl > 0 && (time() - substr($tmp,0,11) > $ttl)){
            $tmp = null;
        }else{
            $tmp = substr($tmp,11);
        }
    }
    return $tmp;
}

/**
 * [WhatIsClient 判断是来自于什么客户端]
 * return "pc" "mobile" "android" "ios" 
 */
function whatIsClient(){  
    $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';  
    $useragent_commentsblock=preg_match('|(.*?)|',$useragent,$matches)>0?$matches[0]:'';   
    $mobile_os_list=array(
        'Google Wireless Transcoder',
        'Windows CE',
        'WindowsCE',
        'Symbian',
        'Android',
        'armv6l',
        'armv5',
        'Mobile',
        'CentOS',
        'mowser',
        'AvantGo',
        'Opera Mobi',
        'J2ME/MIDP',
        'Smartphone',
        'Go.Web',
        'Palm',
        'iPAQ'
    );
    $mobile_token_list=array(
        'Profile/MIDP',
        'Configuration/CLDC-',
        '160×160',
        '176×220',
        '240×240',
        '240×320',
        '320×240',
        'UP.Browser',
        'UP.Link',
        'SymbianOS',
        'PalmOS',
        'PocketPC',
        'SonyEricsson',
        'Nokia',
        'BlackBerry',
        'Vodafone',
        'BenQ',
        'Novarra-Vision',
        'Iris',
        'NetFront',
        'HTC_',
        'Xda_',
        'SAMSUNG-SGH',
        'Wapaka',
        'DoCoMo',
        'iPhone',
        'iPod'
    );
    $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) || CheckSubstrs($mobile_token_list,$useragent); 
    if ($found_mobile){  
        return "mobile";  
    }else{  
        return "pc";  
    }  
}
// 随机生成支付码
function makePaySn($member_id) {
    return mt_rand(10,99)
        . sprintf('%010d',time() - 946656000)
        . sprintf('%03d', (float) microtime() * 1000)
        . sprintf('%03d', (int) $member_id % 1000);
}

//生成卡密
function cardPwd(){
    //种子:
    $seed = "Qdasmn1W2l3k4Epsdf1345oR9uiThjYvbUx654czIgf13dOr52tyPq02weAa86sdSD82kdaFGH0gJKweLtZ8XCVB7N65M";
    $ii = [];
    //获取随机数:
    for($i = 0;$i < 8 ; $i++){
        $ii[] = mt_rand(0,62);
    }
    $result = $seed[$ii[2]].$seed[$ii[4]].$seed[$ii[7]].$seed[$ii[3]].$seed[$ii[1]].$seed[$ii[0]].$seed[$ii[5]].$seed[$ii[6]];
    return $result;
}
//生成优惠券编号
function cardNum(){
    //种子:
    $seed = "401985046120030708090345103541047578931546764545673187313879613476038789131875064073407678946701567690183041230184318433503817635175317817412370581532310202948239016589164061514580143758047015680146806470345801375809163089";
    $ii = [];
    //获取随机数:
    for($i = 0;$i < 10 ; $i++){
        $ii[] = mt_rand(0,221);
    }
    $result = $seed[$ii[2]].$seed[$ii[4]].$seed[$ii[7]].$seed[$ii[3]].$seed[$ii[1]].$seed[$ii[0]].$seed[$ii[5]].$seed[$ii[6]].$seed[$ii[9]].$seed[$ii[8]];
    return $result;
}

// 将数组内的控制转换成空字符
function arrayNullValueToString(array & $array){
    foreach ($array as & $value) {
        if(is_null($value))
            $value = "";
    }
}

/**
 * [nullToStr 将null 值数据转换成空字符]
 * @param  [type] $value [变量]
 */
function nullToStr($value){
    if(is_array($value)){
        array_walk_recursive($value, function(& $value){
            if(is_null($value))
                $value = '';
        });
    } else if($value === null)
        $value = '';

    return $value;
}


// 对数组进行Urlancode编码, 支持递归
function arrayToUrl($array, $index = ''){
    $data  = [];
    $indexName    = $index;
    foreach ($array as $key => $value) {
        if(is_array($value)){
            if($indexName == '')
                $index = $key;
            else
                $index = $indexName . "[$key]";
            $data[] = arrayToUrl($value, $index);
        } else if($indexName != ''){
            $index = urlencode($indexName . "[$key]");
            $data[] = $index.'='.urlencode($value);
        } else{
            $index = urlencode($key);
            $data[] = $index.'='.urlencode($value);
        }
    }
    return join('&', $data);
}

/**
 * 代码运行测试工具
 * @param    [type]     $fn [description]
 * @return   [type]         [description]
 */
function test_code($fn){
    $m1 = microtime();
    $fn();
    $m2 = microtime();
    $m1 = explode(' ', $m1);
    $m2 = explode(' ', $m2);
    $result = [
        'start_sec' => bcmul($m1[1].$m1[0], 10000000),
        'end_sec'   => bcmul($m2[1].$m2[0], 10000000),
    ];
    $result['run_time'] = $result['start_sec'] - $result['end_sec'];
    $result['run_time'] = bcdiv(bcsub($result['end_sec'], $result['start_sec']), 100000000, 6);;
    return $result;
}